import os
from os.path import join, isfile
from timecode import TimeCode
from typing import Tuple, List
import re

def fillTime(start: "TimeCode", end:"TimeCode", known_timecode:"TimeCode", known_time: int, interval) -> Tuple[List[TimeCode], List[int]]: 
    array_timecode = []
    array_time = []
    p_timecode = known_timecode
    if p_timecode > end:
        p_timecode = end
    while p_timecode >= start:

        # print(known_timecode, p_timecode)
        # (known_timecode - p_timecode)
        array_timecode.insert(0, p_timecode)
        array_time.insert(0, int(known_time - (known_timecode - p_timecode).to_frames() * interval))
        p_timecode -= 1
    p_timecode = known_timecode + 1
    if p_timecode < start:
        p_timecode = start
    while p_timecode <= end:
        array_timecode.append(p_timecode)
        array_time.append(int(known_time + (p_timecode - known_timecode).to_frames() * interval))
        p_timecode += 1
        
    return array_timecode, array_time

def writeLtcFile(file_dir, array_timecode, array_time):
    assert len(array_timecode) == len(array_time)
    with open(file_dir, "w") as f:
        for (i, timecode) in enumerate(array_timecode):
            strings = "20092120   "
            strings += str(timecode)
            strings += " |   620842   622315   | "
            strings += str(array_time[i] // 1000000000).zfill(10)
            strings += "."
            strings += str(array_time[i] % 1000000000).zfill(9)
            strings += "  1691037890.467125418 | -0.6dB\n"
            f.write(strings)
            
            
def checkTimecode(ltc_file, check_file, time_name, timecode_name):
    f_ltc = open(ltc_file, "r")
    f_time = open(join(check_file,time_name), "r")
    f_timecode = open(join(check_file, timecode_name), "r")
    
    array_timecode = []
    array_time  = []
    p_timecode = 0
    for line in f_time:
        line.replace("\n","")
        array_time = line.split(",")
    for line in f_timecode:
        if line.startswith("#"):
            continue
        
        strings = line.strip().split()
        if not re.match(r'^\d{8}$', strings[0]):
            continue
        if not re.match(r'^\d{2}:\d{2}:\d{2}:\d{2}', strings[1]):
            continue
           
        array_timecode.append(strings[1])
        
    p_timecode = 0
    print(len(array_time), len(array_timecode))
    for line in f_ltc:
        if line.startswith("#"):
                continue
        strings = line.strip().split()
        timecode = strings[1]
        if timecode == array_timecode[p_timecode]:
            print((int(strings[6].replace(".", "")) - int(array_time[p_timecode])) / 1000000, "ms")
            p_timecode += 1
        if p_timecode >= len(array_time) or p_timecode >= len(array_timecode):
            break
    f_time.close()
    f_timecode.close()
    f_ltc.close()

if __name__ == "__main__":
    ##################################################
    timecode_start_str = "20:40:00:00"
    timecode_end_str = "21:40:00:00"
    frame_rate = 30
    time_interval = 1000000000 / 29.97
    known_timecode_str = "16:52:11:05"
    known_time = 1691225551888456291
    output_file = "/home/liuyun/HHO/multi-camera/data/20230805/ltc2.txt"
    check_file_dir = "/home/liuyun/HHO/multi-camera/data/20230805"
    check_timecode_name = "ego1.txt"
    check_time_name = "ego1_timestamp.txt"
    ####################################################
    
    
    timecode_start = TimeCode.from_string(timecode_start_str, frame_rate)
    timecode_end = TimeCode.from_string(timecode_end_str, frame_rate)
    known_timecode = TimeCode.from_string(known_timecode_str, frame_rate)
    
    array_timecode, array_time = fillTime(timecode_start, timecode_end, known_timecode, known_time, time_interval)
    
    print(len(array_timecode), len(array_time))
    writeLtcFile(output_file, array_timecode, array_time)
    
    # checkTimecode(output_file, check_file_dir, check_time_name, check_timecode_name)
    
    
    
    